
//SONGS.JS
//shows the artists in the library
// Author: Wilco

function songsPage() {}
songsPage.prototype.constructor = songsPage;
songsPage.prototype =
{
    templateData: '',
    songsJSON: '',
    songsData: {},
    title: 'Songs',
	hooksData: null,
	listTmpl: null,
	searchInput: null,
	filers: '',
    loadPage: function()
    {
        this.onOutput = function(title,pageTemplate) { ProcessPageOutput(title,pageTemplate,'',true); }
        this.loadDefaults();
        //Load template data
        LoadFile(SkinDir + 'songs.html', this.onLoadTemplate.bind(this));
    },
    loadDefaults: function()
    {  
       //No Defaults
    },
    onLoadTemplate: function(response)
    {
        this.templateData = response;
        this.loadData();
    },
    loadData: function()
    {
		var url = ServiceDir;
		if (gPageData['songs']['year'])
		{	
            url = url + 'year/' + gPageData['songs']['year'] + '/';
            this.title = gPageData['songs']['year'];
			this.filters = this.filters + '&year=' + gPageData['songs']['year'];
        }
		if (gPageData['songs']['genre'])
		{
            url = url + 'genre/' + gPageData['songs']['genre'] + '/';
            this.title = gPageData['songs']['genre'];
			this.filters = this.filters + '&genre=' + gPageData['songs']['genre'];
        }
		if (gPageData['songs']['artist'])
		{
            url = url + 'artist/' + gPageData['songs']['artist'] + '/';
            this.title = gPageData['songs']['artist'];
			this.filters = this.filters + '&artist=' + gPageData['songs']['artist'];
        }
		if (gPageData['songs']['album'])
		{
            url = url + 'album/' + gPageData['songs']['album'] + '/';
            this.title = gPageData['songs']['album'];
			this.filters = this.filters + '&album=' + gPageData['songs']['album'];
        }
		
        url = url + ''; 
        LoadFile(url, this.onLoadData.bind(this));
    },
    onLoadData: function(response)
    {
       this.songsJSON = response;
       this.generateOutput();
	   
		//Load hooks data
		var url = ServiceDir + 'hooks/mediaItem'; 
        LoadFile(url, this.onLoadHooks.bind(this));
    },
	onLoadHooks: function(response)
	{
		this.hooksData = eval("(" + response + ")");
		var style = (this.hooksData.length > 0) ? 'block' : 'none';
		
		$('.menuDetailsButton').each(function() { 
		this.style.display = style; 
		});
	},
    generateOutput: function()
    {
		
        try
        {    this.songsData = eval("(" + this.songsJSON + ")"); }
        catch (e)
        {    showError('Cannot understand service data'); return; }        

		//set indexes before we sort!
		for (var i=0;i<this.songsData.tracks.length;i++)
		{
			this.songsData.tracks[i].index = i;
		}
		
		var tmpl = new Template();
		tmpl.load(this.templateData);
        
        //TODO: sort here?
        this.listTmpl = tmpl.removeSubTemplate('list');
        this.songsData.tracks.sort(function(a,b){ if (a.name<b.name) return -1; else if (a.name>b.name) return 1; else return 0;});
        
        this.onOutput(this.title,tmpl);
		
		//Hook events
		$('#SearchInput').bind('keyup',SearchUpdate);
		
		this.updateList(this.songsData.tracks);
    },
	updateList: function(songs)
	{
		tmpl = this.listTmpl.clone();
		var headertmpl = tmpl.removeSubTemplate('header');
		var itemtmpl = tmpl.removeSubTemplate('item');
        
		var tmplData = { item: [] };
        var items = [];
        var sortname;
        var prevsortname = '';
        var newtmpl = null;
		for(var i=0;i<songs.length;i++)
		{
            if (songs.length > 50)
            {
                if (songs[i].name == null) continue; //FIXME: this shouldnt happen
                
                sortname = songs[i].name.substring(0,1).toLowerCase();
                
                
                if (sortname != prevsortname)
                {
                    newtmpl = headertmpl.clone();
                    newtmpl.addData({ 'group_title': sortname.toUpperCase() });
                    items.push(newtmpl);
                    prevsortname = sortname;
                }
            }
                
            newtmpl = itemtmpl.clone();
            newtmpl.addData({    title: songs[i].name,
                            song_uri: encodeURIComponent(songs[i].name),
							index: 		songs[i].index,
                        });
            items.push(newtmpl);
		}
		
		tmpl.addSubTemplate('item',items);
		document.getElementById('pagelist').innerHTML = tmpl.parse();
	},
	runSearch: function(searchStr)
	{
		var songs = this.songsData.tracks;
		songs = LocalSearch(songs,['name'],searchStr);
		this.updateList(songs);
	},
    onOutput: function(){},
}
function SearchUpdate(eventObj)
{
	var str = $('#SearchInput').val();
	gCurrentPage.runSearch(str);
}

function SongItemButton_Click(el,i)
{
	CreateMediaItemMenu(gCurrentPage.hooksData,gCurrentPage.songsData.tracks[i]);
	ShowMenu();
}


gLastScriptLoaded = new songsPage();
gScriptLoaded();